﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Configuration
{
    public class EncryptedConfigurationProvider : ConfigurationProvider
    {
        private readonly string _encryptionKey;
        private readonly string _filePath;

        public EncryptedConfigurationProvider(string filePath, string encryptionKey)
        {
            _filePath = filePath;
            _encryptionKey = encryptionKey ?? GetDefaultEncryptionKey();
        }

        public override void Load()
        {
            // 使用 JsonConfigurationProvider 读取原始文件
            var jsonProvider = new JsonConfigurationProvider(
                new JsonConfigurationSource
                {
                    Path = _filePath,
                    Optional = false
                });

            var data = new Dictionary<string, string>();
            jsonProvider.Load();

            // 获取原始数据并解密
            foreach (var key in jsonProvider.GetChildKeys(Enumerable.Empty<string>(), null))
            {
                var value = jsonProvider.TryGet(key, out var tempValue) ? tempValue : null;
                if (value != null && key.Contains("Password", StringComparison.OrdinalIgnoreCase))
                {
                    data[key] = DecryptValue(value);
                }
                else
                {
                    data[key] = value;
                }
            }

            Data = data;
        }

        private string DecryptValue(string encryptedValue)
        {
            try
            {
                // 检查是否是加密格式
                if (encryptedValue.StartsWith("enc:"))
                {
                    var actualEncryptedValue = encryptedValue.Substring(4);
                    return EncryptionHelper.Decrypt(actualEncryptedValue, _encryptionKey);
                }
                return encryptedValue;
            }
            catch
            {
                return encryptedValue;
            }
        }

        private static string GetDefaultEncryptionKey()
        {
            // 从环境变量获取或返回默认值
            return Environment.GetEnvironmentVariable("APP_ENCRYPTION_KEY")
                   ?? "default-32-byte-encryption-key!!";
        }
    }
}
